package com.example.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.JwtInterceptor;
import com.example.entity.Devices;
import com.example.entity.Params;
import com.example.exception.CustomException;
import com.example.repository.DevicesMapper;
import com.example.util.JacksonUtil;
import com.example.util.SpringUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class DevicesService extends ServiceImpl<DevicesMapper, Devices> {

    @Resource
    private DevicesMapper devicesMapper;

    @Resource
    private KafkaProducerService kafkaProducerService;

    public List<Devices> findAll() {
        return devicesMapper.findAll();
    }

    public PageInfo<Devices> findBySearchOfDevices(Params params) {
        PageHelper.startPage(params.getPageNum(), params.getPageSize());
        List<Devices> search = devicesMapper.findBySearchOfDevices(params);
        return PageInfo.of(search);
    }

    public void addDevice(Devices device) {
        Devices newDevice = devicesMapper.findDeviceNameByDeviceId(device.getDeviceId());
        if (newDevice != null) {
            throw new CustomException("该设备已存在，请勿重复添加！");
        }
        if (device.getDeviceName() == null || "".equals(device.getDeviceName())) {
            throw new CustomException("请填写设备名称！");
        }
        if (device.getDeviceType() == null || "".equals(device.getDeviceType())) {
            throw new CustomException("请填写设备类别！");
        }
        if (device.getStatus() == null || "".equals(device.getStatus())) {
            throw new CustomException("请选择设备状态！");
        }
        if (device.getLocation() == null || "".equals(device.getLocation())) {
            throw new CustomException("请填写设备位置！");
        }
        if (device.getThreshold() == null) {
            throw new CustomException("请设置设备阈值！");
        }
        devicesMapper.addDevice(device);

    }

    public void removeDevice(String deviceId) {
        devicesMapper.deleteById(deviceId);
    }

    public void updateDevice(Devices devices) {
        devicesMapper.updateById(devices);
    }

    public Devices findByDeviceId(String deviceId) {
        return devicesMapper.findDeviceNameByDeviceId(deviceId);
    }

    // 获取设备名称（该方法是在编辑时根据单个deviceId查询deviceName，每次只查一个）
    String getDeviceNameById(String deviceId) {
        Devices device = devicesMapper.findDeviceNameByDeviceId(deviceId);
        return device != null ? device.getDeviceName() : "Unknown";
    }

    public List<Map<String, Object>> initPie() {
        return devicesMapper.initPie();
    }

    public void superviseDeviceInAutoMode(Collection<Devices> devices) {
        KafkaProducerService.MessageBody before = KafkaProducerService.MessageBody.newInstance();
        if (CollectionUtils.isEmpty(devices)) {
            return;
        }
        for (Devices device : devices) {
            //判断是否达到阈值的接口方法
            DeviceScheduleThreshold deviceThresholdService = getThreshold(device.getDeviceType());
            device.setStatus(deviceThresholdService.threshold(device) ? "1" : "0");
            saveOrUpdate(device);
            DeviceValueUpdate valueUpdateService = getValueUpdate(device.getDeviceType());
            valueUpdateService.statusUpdate(device.getStatus());
        }
        KafkaProducerService.MessageBody current = KafkaProducerService.MessageBody.newInstance();
        if (!KafkaProducerService.MessageBody.same(before, current)) {
            kafkaProducerService.sendMessage(current);
            log.info("message has been sent through 'A' mode, detail: {}", JacksonUtil.encode(current));
        }
    }


    public static DeviceScheduleThreshold getThreshold(String deviceType) {
        DeviceScheduleThreshold deviceScheduleThreshold;
        switch (deviceType) {
            case "AC":
                deviceScheduleThreshold = SpringUtil.getBean(FanService.class);
                break;
            case "CURTAIN":
                deviceScheduleThreshold = SpringUtil.getBean(StepperMotorService.class);
                break;
            case "BUZZER":
                deviceScheduleThreshold = SpringUtil.getBean(BuzzerService.class);
                break;
            case "GREEN_LED":
                deviceScheduleThreshold = SpringUtil.getBean(GreenLedService.class);
                break;
            case "ORANGE_LED":
                deviceScheduleThreshold = SpringUtil.getBean(OrangeLedService.class);
                break;
            default:
                throw new CustomException("不可识别的设备类型");
        }
        return deviceScheduleThreshold;
    }

    public static DeviceValueUpdate getValueUpdate(String deviceType) {
        DeviceValueUpdate deviceValueUpdate;
        switch (deviceType) {
            case "AC":
                deviceValueUpdate = SpringUtil.getBean(FanService.class);
                break;
            case "CURTAIN":
                deviceValueUpdate = SpringUtil.getBean(StepperMotorService.class);
                break;
            case "BUZZER":
                deviceValueUpdate = SpringUtil.getBean(BuzzerService.class);
                break;
            case "GREEN_LED":
                deviceValueUpdate = SpringUtil.getBean(GreenLedService.class);
                break;
            case "ORANGE_LED":
                deviceValueUpdate = SpringUtil.getBean(OrangeLedService.class);
                break;
            default:
                throw new CustomException("不可识别的设备类型");
        }
        return deviceValueUpdate;
    }



}
